<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SuperSubsidyDayGoodsController extends Controller
{
    const CACHE_DATA_EXPIRE_TIME = 30 * 86400;

    public function index(Request $request, Content $content)
    {
        $info = ['file' => ''];
        $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_GOODS);
        $resContent = $redis->getCache();
        if ($resContent) {
            $cacheKey = $redis->getKey();
            $time = $redis->getTtl();

            $days = floor($time / 86400);
            $hourSeconds = $time % 86400;
            $hours = floor($hourSeconds / 3600);
            $minuteSeconds = $hourSeconds % 3600;
            $minutes = floor($minuteSeconds / 60);
            $remainingSeconds = $minuteSeconds % 60;
            $seconds = ceil($remainingSeconds);
            $ttl = date('Y-m-d H:i:s', (time() + $time)) . '。剩余时间：' . $days . '天' . $hours . '小时' . $minutes . '分' . $seconds . '秒。';
            $info['goods'] = $resContent;
            $info['addtime'] = date('Y-m-d H:i:s', time() - (self::CACHE_DATA_EXPIRE_TIME - $time));
            $info['ttl'] = $ttl;
            $info['cache_key'] = $cacheKey;
        }
        $form = new Form($info);
        if (isset($info['goods'])) {
            $form->text('addtime', '数据更新时间')->readonly();
            $form->text('ttl', '数据有效期')->readonly();
            $form->text('cache_key', '缓存key')->readonly();
            $form->textarea('goods', '数据预览')->rows(20);
        }
        $form->file('file', '上传商品文件')->help('文件格式为：excel文件');
        $form->action('/admin/SuperSubsidy/superSubsidyDay/goods/save');
        $tab = new Tab();
        $tab->add('补贴活动V1', '<a target="_blank" href="/admin/SuperSubsidy/superSubsidyDay/goods/excel">下载模版</a>' . $form->render(), true);
        $tab->addLink('补贴活动v2', url('/admin/SuperSubsidy/superSubsidyDay/goods/v2'));
        $tab->addLink('补贴活动v3', url('/admin/SuperSubsidy/superSubsidyDay/goods/v3'));
        return $content
            ->header('上传超级补贴商品文件')
            ->description(' ')
            ->breadcrumb(
                ['text' => '上传超级补贴商品文件']
            )
            ->row($tab);
    }

    public function save(Request $request)
    {
        try {
            $file = $request->file('file');
            $fileName = '/tmp/superSubsidyDayGoods-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            $spreadsheet = IOFactory::load($fileName);
            $seckillData = $this->reloadSeckillGoods($spreadsheet);
            $onlineData = $this->reloadAllGoods($spreadsheet);
            $data = [
                'seckill_data' => $seckillData,
                'online_data' => $onlineData
            ];

            $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_GOODS);
            $redis->setCache($data);
            $redis->setExpireTime(self::CACHE_DATA_EXPIRE_TIME);

            if ($res) {
                $success = new MessageBag([
                    'title' => '上传成功'
                ]);
                return redirect('/admin/SuperSubsidy/superSubsidyDay/goods')->with(compact('success'));
            } else {
                throw new \Exception('保存文件失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '上传失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function indexExcel(Request $request)
    {
        $fileNmae = dirname(__FILE__) . DIRECTORY_SEPARATOR . '超级补贴V1商品数据.xlsx';
        $file = fopen($fileNmae, "rb");
        Header("Content-type:  application/octet-stream ");
        Header("Accept-Ranges:  bytes ");
        Header("Content-Disposition:  attachment;  filename= 超级补贴V1商品数据.xlsx");
        while (!feof($file)) {
            echo fread($file, 8192);
            ob_flush();
            flush();
        }
        fclose($file);
    }

    public function indexV(Request $request, Content $content, $v = 'v2')
    {
        $info = ['file' => ''];
        $ver = $this->getVer($v);

        $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_GOODS);
        $resContent = $redis->getCache($ver);

        if ($resContent) {
            $cacheKey = $redis->getKey($ver);
            $time = $redis->getTtl($ver);

            $days = floor($time / 86400);
            $hourSeconds = $time % 86400;
            $hours = floor($hourSeconds / 3600);
            $minuteSeconds = $hourSeconds % 3600;
            $minutes = floor($minuteSeconds / 60);
            $remainingSeconds = $minuteSeconds % 60;
            $seconds = ceil($remainingSeconds);
            $ttl = date('Y-m-d H:i:s', (time() + $time)) . '。剩余时间：' . $days . '天' . $hours . '小时' . $minutes . '分' . $seconds . '秒。';
            $info['cache_key'] = $cacheKey;
            $info['goods'] = $resContent;
            $info['addtime'] = date('Y-m-d H:i:s', time() - (self::CACHE_DATA_EXPIRE_TIME - $time));
            $info['ttl'] = $ttl;
        }
        $form = new Form($info);
        if (isset($info['goods'])) {
            $form->text('addtime', '数据更新时间')->readonly();
            $form->text('ttl', '数据有效期')->readonly();
            $form->text('cache_key', '缓存key')->readonly();
            $form->textarea('goods', '数据预览')->rows(20);
        }
        $form->file('file', '上传商品文件')->help('文件格式为：excel文件');
        $form->action('/admin/SuperSubsidy/superSubsidyDay/goods/save/' . $v);
        $tab = new Tab();
        $tab->addLink('补贴活动V1', url('/admin/SuperSubsidy/superSubsidyDay/goods'));
        if ($ver == 2) {
            $tab->add('补贴活动v2', '<a target="_blank" href="/admin/SuperSubsidy/superSubsidyDay/goods/' . $v . '/excel">下载模版</a>' . $form->render(), true);
            $tab->addLink('补贴活动v3', url('/admin/SuperSubsidy/superSubsidyDay/goods/v3'));
        } elseif ($ver == 3) {
            $tab->addLink('补贴活动v2', url('/admin/SuperSubsidy/superSubsidyDay/goods/v2'));
            $tab->add('补贴活动v3', '<a target="_blank" href="/admin/SuperSubsidy/superSubsidyDay/goods/' . $v . '/excel">下载模版</a>' . $form->render(), true);
        }
        return $content
            ->header('上传超级补贴' . $v . '商品文件')
            ->description(' ')
            ->breadcrumb(
                ['text' => '上传超级补贴' . $v . '商品文件']
            )
            ->row($tab);
    }

    public function indexVExcel(Request $request, $v = 'v2')
    {
        $ver = $this->getVer($v);
        $fileNmae = dirname(__FILE__) . DIRECTORY_SEPARATOR . '补贴日第二期商品数据模板.xlsx';
        $file = fopen($fileNmae, "rb");
        $name = '补贴日第' . $ver . '期商品数据模板.xlsx';
        Header("Content-type:  application/octet-stream ");
        Header("Accept-Ranges:  bytes ");
        Header("Content-Disposition:  attachment;  filename= " . $name);
        while (!feof($file)) {
            echo fread($file, 8192);
            ob_flush();
            flush();
        }
        fclose($file);
    }

    public function saveV(Request $request, $v = 'v2')
    {
        try {
            $file = $request->file('file');
            $fileName = '/tmp/superSubsidyDayGoods-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            $spreadsheet = IOFactory::load($fileName);
            $couponData = [];
            $todayRecommendData = [];
            $categoryData = [];
            $spreadsheet->setActiveSheetIndex(0);
            $allSheets = $spreadsheet->getAllSheets();
            $categoryId = 1;
            foreach ($allSheets as $sheet) {
                $sheetTitle = $sheet->getTitle();
                $sheetData = $sheet->toArray(null, true, true, true);
                if ('优惠券' == trim($sheetTitle)) {
                    $couponData = $this->getCouponData($sheetData);
                } else if ('今日住友推荐' == trim($sheetTitle)) {
                    $todayRecommendData = $this->getTodayRecommendData($sheetData);
                } else {
                    $categoryData[] = [
                        'category_id' => $categoryId,
                        'category' => $sheetTitle,
                        'list' => $this->getTabCategoryData($sheetData)
                    ];
                    $categoryId++;
                }
            }
            $data = [
                'coupon_data' => $couponData,
                'today_data' => $todayRecommendData,
                'category_data' => $categoryData
            ];
            $ver = $this->getVer($v);

            $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_GOODS);
            $redis->setCache($data, $ver);
            $redis->setExpireTime(self::CACHE_DATA_EXPIRE_TIME, $ver);

            if ($res) {
                $success = new MessageBag([
                    'title' => '上传成功'
                ]);
                return redirect('/admin/SuperSubsidy/superSubsidyDay/goods/' . $v)->with(compact('success'));
            } else {
                throw new \Exception('保存文件失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '上传失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    private function getVer($v)
    {
        if ('v3' == $v) {
            $ver = 3;
        } else {
            $ver = 2;
        }
        return $ver;
    }

    private function reloadSeckillGoods($spreadsheet)
    {
        $data = [];
        $spreadsheet->setActiveSheetIndex(0);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        if ($sheetData && is_array($sheetData)) {
            foreach ($sheetData as $i => $item) {
                if ($i <= 1) {
                    continue;
                }
                $itemId = trim($item['A']);
                $alias = trim($item['C']);
                $seckillId = trim($item['D']);
                $brand = trim($item['E']);
                $title = trim($item['F']);
                $title = $brand . ' | ' . $title;
                $desc = trim($item['G']);
                $imgs = $item['H'];
                $imgList = explode("\n", $imgs);
                foreach ($imgList as $key => $img) {
                    $imgList[$key] = trim($img);
                }
                $price = trim($item['I']);
                $seckillPrice = trim($item['J']);
                $miniUrl = trim($item['K']);
                $shareMiniUrl = trim($item['L']);
                $h5Url = trim($item['M']);
                $beginTime = trim($item['N']);
                $beginTime = date('Y-m-d H:i:s', strtotime($beginTime));
                $pos = trim($item['O']);
                $pos = is_numeric($pos) ? $pos : 0;
                $stock = trim($item['P']);
                if ($itemId) {
                    $info = [
                        'item_id' => $itemId,
                        'alias' => $alias,
                        'seckill_id' => $seckillId,
                        'title' => $title,
                        'desc' => $desc,
                        'price' => $price,//原价
                        'seckill_price' => $seckillPrice,//秒杀价
                        'begin_time' => $beginTime,
                        'img_list' => $imgList,
                        'wechat_mini_link' => $miniUrl,
                        'share_wechat_mini_link' => $shareMiniUrl,
                        'original_link' => $h5Url,
                        'pos' => $pos,
                        'stock' => $stock
                    ];
                    $data[] = $info;
                }
            }
        }
        return $data;
    }

    private function reloadAllGoods($spreadsheet)
    {
        $data = [];
        $avatarArr = \Biz\module\Classes\wiki\Wiki::getRandUserCoverImg(300);
        $avatarArr = array_column($avatarArr, 'cover_img');
        $spreadsheet->setActiveSheetIndex(1);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        if ($sheetData && is_array($sheetData)) {
            foreach ($sheetData as $i => $item) {
                if ($i <= 1) {
                    continue;
                }
                $itemId = trim($item['A']);
                $alias = trim($item['C']);
                $brand = trim($item['D']);
                $title = trim($item['E']);
                $title = $brand . ' | ' . $title;
                $imgs = $item['F'];
                $imgList = explode("\n", $imgs);
                foreach ($imgList as $key => $img) {
                    $imgList[$key] = trim($img);
                }
                $price = trim($item['G']);
                $reducePrice = trim($item['H']);
                $subsidyPrice = trim($item['I']);
                $comment = $item['J'];
                $commentsList = explode("\n", $comment);
                foreach ($commentsList as $key => $comment) {
                    $commentsList[$key] = trim($comment);
                }
                $comments = [];
                foreach ($commentsList as $content) {
                    $avatar = "https://img.haohaozhu.cn/Pic-imageShow/sq_270/0004hogc?iv=1&v=1";
                    $randIndex = rand(0, count($avatarArr));
                    $avatar = $avatarArr[$randIndex] ?: $avatar;
                    unset($avatarArr[$randIndex]);
                    $comments[] = [
                        'avatar' => $avatar,
                        'content' => $content,
                    ];
                }
                $miniUrl = trim($item['K']);
                $shareMiniUrl = trim($item['L']);
                $h5Url = trim($item['M']);
                $pos = trim($item['N']);
                $pos = is_numeric($pos) ? $pos : 0;
                if ($itemId) {
                    $info = [
                        'item_id' => $itemId,
                        'alias' => $alias,
                        'title' => $title,
                        'price' => $price,//原价
                        'reduce_price' => $reducePrice,//直降价
                        'subsidy_price' => $subsidyPrice,//补贴价
                        'img_list' => $imgList,
                        'wechat_mini_link' => $miniUrl,
                        'share_wechat_mini_link' => $shareMiniUrl,
                        'original_link' => $h5Url,
                        'comment' => $comments,//评价
                        'pos' => $pos
                    ];
                    $data[] = $info;
                }
            }
        }
        return $data;
    }

    private function getCouponData($sheetData)
    {
        $data = [];
        if ($sheetData && is_array($sheetData)) {
            foreach ($sheetData as $i => $item) {
                if ($i <= 1) {
                    continue;
                }
                $info = [
                    'coupon_id' => trim($item['A']),
                    'wechat_mini_link' => trim($item['B']),
                    'original_link' => trim($item['C']),
                    'receive_date' => trim($item['D'])
                ];
                $data[] = $info;
            }
        }
        return $data;
    }

    private function getTodayRecommendData($sheetData)
    {
        $data = [];
        if ($sheetData && is_array($sheetData)) {
            foreach ($sheetData as $i => $item) {
                if ($i <= 1) {
                    continue;
                }
                $itemId = trim($item['A']);
                $alias = trim($item['C']);
                $title = trim($item['D']);
                $recommendation = trim($item['E']);
                $imgs = $item['F'];
                $imgList = explode("\n", $imgs);
                foreach ($imgList as $key => $img) {
                    $imgList[$key] = trim($img);
                }
                $price = trim($item['G']);
                $subsidyPrice = trim($item['H']);
                $miniUrl = trim($item['I']);
                $h5Url = trim($item['J']);
                $pos = trim($item['K']);
                $pos = is_numeric($pos) ? $pos : 0;
                $hasFullDiscount = trim($item['L']);
                $hasFullDiscount = ($hasFullDiscount == '是') ? 1 : 0;
                if ($itemId) {
                    $info = [
                        'item_id' => $itemId,
                        'alias' => $alias,
                        'title' => $title,
                        'recommendation' => $recommendation,//推荐理由
                        'price' => $price,//原价
                        'subsidy_price' => $subsidyPrice,//补贴价
                        'img_list' => $imgList,
                        'wechat_mini_link' => $miniUrl,
                        'original_link' => $h5Url,
                        'pos' => $pos,
                        'has_full_discount' => $hasFullDiscount,//是否参与满减
                    ];
                    $data[] = $info;
                }
            }
        }
        return $data;
    }

    private function getTabCategoryData($sheetData)
    {
        $data = [];
        if ($sheetData && is_array($sheetData)) {
            foreach ($sheetData as $i => $item) {
                if ($i <= 1) {
                    continue;
                }
                $itemId = trim($item['A']);
                $alias = trim($item['C']);
                $brand = trim($item['D']);
                $title = trim($item['E']);
                $title = $brand . ' | ' . $title;
                $desc = trim($item['F']);
                $imgs = $item['G'];
                $imgList = explode("\n", $imgs);
                foreach ($imgList as $key => $img) {
                    $imgList[$key] = trim($img);
                }
                $price = trim($item['H']);
                $subsidyPrice = trim($item['I']);
                $miniUrl = trim($item['J']);
                $h5Url = trim($item['K']);
                $pos = trim($item['L']);
                $pos = is_numeric($pos) ? $pos : 0;
                $hasFullDiscount = trim($item['M']);
                $hasFullDiscount = ($hasFullDiscount == '是') ? 1 : 0;
                if ($itemId) {
                    $info = [
                        'item_id' => $itemId,
                        'alias' => $alias,
                        'title' => $title,
                        'desc' => $desc,
                        'img_list' => $imgList,
                        'price' => $price,//原价
                        'subsidy_price' => $subsidyPrice,//补贴价
                        'wechat_mini_link' => $miniUrl,
                        'original_link' => $h5Url,
                        'pos' => $pos,
                        'has_full_discount' => $hasFullDiscount,//是否参与满减
                    ];
                    $data[] = $info;
                }
            }
        }
        return $data;
    }
}